package com.robusta.cityuate.activities;

import java.util.Calendar;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Toast;

import com.actionbarsherlock.view.Window;
import com.robusta.cityuate.R;
import com.robusta.cityuate.base.CityuateGuestActivity;
import com.robusta.cityuate.dialogs.CountryPickerFragment;
import com.robusta.cityuate.dialogs.CountryPickerFragment.CountryPickerCallback;
import com.robusta.cityuate.dialogs.DatePickerFragment;
import com.robusta.cityuate.infoActivities.CityauteTermsAndConditions;
import com.robusta.cityuate.objects.Country;
import com.robusta.cityuate.services.CityuateBroadCastReceiver;
import com.robusta.cityuate.services.HTTPService;
import com.robusta.cityuate.services.RegistrationService;
import com.robusta.cityuate.utils.ConnectionUtils;
import com.robusta.cityuate.utils.TimeUtils;

public class RegistrationActivity extends CityuateGuestActivity implements
		TextWatcher,CountryPickerCallback {

	// private static final int DATE_OF_BIRTH_DIALOG = 1;

	private static final String TAG = RegistrationActivity.class.getName();

	private Context mContext = this;
	private CheckBox conditionsCheckbox;
	private boolean isFilled = false;
	private Button regButton;
	// private int dyear, dmonth, dday;
	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle) "user":
	 * {"first_name":"Foo", "last_name":"Bar", "username":"foobar",
	 * "email":"foo@bar.com", "country_id":"44", "password":"samplepass",
	 * "mobile_number":"01001123412", "city":"Cairo", "district":"Al Maadi",
	 * "street":"Foo Bar Dan St..", "building_number":"123", "zip_code":"11474"
	 * ,"dob(1i)":"1991" ,"dob(2i)":"9", "dob(3i)":"23"
	 */

	private EditText dateOfBirthField;
	private EditText firstNameField;
	private EditText lastNameField;
	private EditText usernameField;
	private EditText emailField;
	private EditText pwdField;
	private EditText pwdConfirmField;
	private EditText countryField;
	private EditText mobileNumberField;
	private EditText cityField;
	private EditText districtField;
	private EditText streetField;
	private EditText buildingField;
	private EditText zipCodeField;
	private Country mCountry;

	private final String REG_EMAIL = "email";
	private final String REG_PWD = "password";
	private final String REG_FIRST_NAME = "first_name";
	private final String REG_LAST_NAME = "last_name";
	private final String REG_COUNTRY_ID = "country_id";
	private final String REG_USERNAME = "username";
	private final String REG_MOBILE_NUMBER = "mobile_number";
	private final String REG_CITY = "city";
	private final String REG_DISTRICT = "district";
	private final String REG_STREET = "street";
	private final String REG_BUILDING_NUMBER = "building_number";
	private final String REG_ZIP_CODE = "zip_code";
	private final String REG_DOB_1I = "dob(1i)";
	private final String REG_DOB_2I = "dob(2i)";
	private final String REG_DOB_3I = "dob(3i)";
	private CityuateBroadCastReceiver receiver = new CityuateBroadCastReceiver() {

		@Override
		public void onSuccess() {
			registrationSuccess();
		}

		@Override
		public void onFailure() {
			registrationFail();
		}

		@Override
		public void onCancel() {
			setSupportProgressBarIndeterminateVisibility(false);
			enableView();
			ConnectionUtils.clearConnection(mContext, TAG);
		}

	};

	// private int country_id;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setSupportProgressBarIndeterminateVisibility(false);
		super.onCreate(savedInstanceState);

		setContentView(R.layout.registration_view);
		dateOfBirthField = (EditText) findViewById(R.id.dateofbirth);
		mCountry = new Country();
		// registration submit button
		regButton = (Button) findViewById(R.id.btn_register);
		regButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				fireRegistrationService();
			}

		});

		// condition check box
		conditionsCheckbox = (CheckBox) findViewById(R.id.reg_conditions);
		conditionsCheckbox
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {
					@Override
					public void onCheckedChanged(CompoundButton arg0,
							boolean isChecked) {
						// enable and disable registration button with
						regButton.setEnabled(isFilled
								&& conditionsCheckbox.isChecked());
					}
				});

		firstNameField = (EditText) findViewById(R.id.firstname);
		lastNameField = (EditText) findViewById(R.id.lastname);
		usernameField = (EditText) findViewById(R.id.usrname);
		emailField = (EditText) findViewById(R.id.email);
		pwdField = (EditText) findViewById(R.id.reg_pwd_f);
		pwdConfirmField = (EditText) findViewById(R.id.reg_pwd_s);
		countryField = (EditText) findViewById(R.id.country);
		mobileNumberField = (EditText) findViewById(R.id.mobilnum);
		cityField = (EditText) findViewById(R.id.city);
		districtField = (EditText) findViewById(R.id.district);
		streetField = (EditText) findViewById(R.id.street);
		buildingField = (EditText) findViewById(R.id.buildnum);
		zipCodeField = (EditText) findViewById(R.id.zipcode);

		dateOfBirthField.addTextChangedListener(this);
		firstNameField.addTextChangedListener(this);
		lastNameField.addTextChangedListener(this);
		usernameField.addTextChangedListener(this);
		emailField.addTextChangedListener(this);
		pwdField.addTextChangedListener(this);
		pwdConfirmField.addTextChangedListener(this);
		countryField.addTextChangedListener(this);
		mobileNumberField.addTextChangedListener(this);
		cityField.addTextChangedListener(this);
		districtField.addTextChangedListener(this);
		streetField.addTextChangedListener(this);
		buildingField.addTextChangedListener(this);
		zipCodeField.addTextChangedListener(this);

		// making country field noneditable
		countryField.setFocusable(false);
		countryField.setFocusableInTouchMode(false);
		countryField.setKeyListener(null);
		// Edit conntry through activity
		countryField.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// initialize intent to get
				// Intent countryIntent = new Intent(mContext,
				// CountryPickerActivity.class);
				// startActivityForResult(countryIntent,
				// CountryPickerActivity.CHOOSE_COUNTY_ACTIVITY);
				CountryPickerFragment countrypick = CountryPickerFragment
						.getInstance(R.id.country, mCountry);
				countrypick.show(getSupportFragmentManager(), "Pick_Country");
			}
		});
		getSupportActionBar().setSubtitle(R.string.registration);
	}

	@Override
	protected void onPause() {
		Log.e("onPause", "OnPause");
		unregisterReceiver(receiver);
		if (!ConnectionUtils.isConnecting(mContext, TAG)) {
			ConnectionUtils.clearConnection(mContext, TAG);
		}

		super.onPause();
	}

	@Override
	protected void onResume() {
		Log.d(TAG, "onResume");
		// initiate the receiver
		IntentFilter filter = new IntentFilter();
		filter.addAction(TAG);
		registerReceiver(receiver, filter);
		// No current connection
		if (!ConnectionUtils.isConnecting(mContext, TAG))
		// it was connected
		{
			if (ConnectionUtils.wasConnected(mContext, TAG))
				// connection was successful
				if (ConnectionUtils.isResultSuccessful(mContext, TAG))
					registrationSuccess();
				else
					// it failed
					registrationFail();
		} else { // there is an active connection
			setSupportProgressBarIndeterminateVisibility(true);
			disableView();

		}
		super.onResume();
	}

	private void fireRegistrationService() {

		// Case passwords don't match.
		if (!pwdConfirmField.getText().toString()
				.equals(pwdField.getText().toString())) {// show failure message
			Toast.makeText(mContext, getString(R.string.reg_pwd_match_err),
					Toast.LENGTH_LONG).show();
			return;
		}

		// Check if no connection pop up a dialog
		if (!ConnectionUtils.isNetworkAvailable(mContext)) {
			// No connection
			ConnectionUtils.showNoConnectionDialog(mContext);
			return;
		} else { // Connection is available

			// Start loading dialog and connecting variables
			setSupportProgressBarIndeterminateVisibility(true);
			disableView();
			// start back-ground service to handle registration process
			Intent backgroud_regService = new Intent(this,
					RegistrationService.class);
			backgroud_regService.setAction(TAG);

			backgroud_regService.putExtra(REG_EMAIL, emailField.getText()
					.toString());
			backgroud_regService.putExtra(REG_PWD, pwdField.getText()
					.toString());
			backgroud_regService.putExtra(REG_BUILDING_NUMBER, buildingField
					.getText().toString());
			backgroud_regService.putExtra(REG_CITY, cityField.getText()
					.toString());
			backgroud_regService.putExtra(REG_DISTRICT, districtField.getText()
					.toString());
			backgroud_regService.putExtra(REG_FIRST_NAME, firstNameField
					.getText().toString());
			backgroud_regService.putExtra(REG_LAST_NAME, lastNameField
					.getText().toString());
			backgroud_regService.putExtra(REG_USERNAME, usernameField.getText()
					.toString());
			backgroud_regService.putExtra(REG_DISTRICT, districtField.getText()
					.toString());
			backgroud_regService.putExtra(REG_MOBILE_NUMBER, mobileNumberField
					.getText().toString());
			backgroud_regService.putExtra(REG_STREET, streetField.getText()
					.toString());
			backgroud_regService.putExtra(REG_ZIP_CODE, zipCodeField.getText()
					.toString());

			Calendar c = TimeUtils.getCalendarFromFormat(dateOfBirthField
					.getText().toString(), "MMM dd, yyyy");
			backgroud_regService.putExtra(REG_DOB_1I, c.get(Calendar.YEAR));
			backgroud_regService.putExtra(REG_DOB_2I, c.get(Calendar.MONTH)+1);
			backgroud_regService.putExtra(REG_DOB_3I,
					c.get(Calendar.DAY_OF_MONTH));

			backgroud_regService.putExtra(REG_COUNTRY_ID, mCountry.getId());

			startService(backgroud_regService);
			Log.e(TAG, "Fired Registration service");

		}

	}

	/**
	 * registration success show a Toast and switch to Login Activity
	 * 
	 */
	private void registrationSuccess() {
		enableView();
		setSupportProgressBarIndeterminateVisibility(false);
		Log.d(TAG, "RegSuccess method");
		Toast.makeText(mContext, getString(R.string.reg_success),
				Toast.LENGTH_LONG).show();
		setResult(RESULT_OK);

		finish();
	}

	/**
	 * registration fail scenario
	 */
	private void registrationFail() {
		Log.d(TAG, "Registration Fail method");
		
		enableView();
		setSupportProgressBarIndeterminateVisibility(false);
		// show failure message
		Toast.makeText(mContext, ConnectionUtils.getExtra(mContext, TAG),
				Toast.LENGTH_LONG).show();
		ConnectionUtils.clearConnection(mContext, TAG);

	}

	@Override
	public void afterTextChanged(Editable arg0) {
		if (dateOfBirthField.getText().length() != 0
				&& firstNameField.getText().length() != 0
				&& lastNameField.getText().length() != 0
				&& usernameField.getText().length() != 0
				&& emailField.getText().length() != 0
				&& pwdField.getText().length() != 0
				&& pwdConfirmField.getText().length() != 0
				&& countryField.getText().length() != 0
				&& mobileNumberField.getText().length() != 0
				&& cityField.getText().length() != 0
				&& districtField.getText().length() != 0
				&& streetField.getText().length() != 0
				&& buildingField.getText().length() != 0
				&& zipCodeField.getText().length() != 0)
			isFilled = true;
		else
			isFilled = false;

		regButton.setEnabled(isFilled && conditionsCheckbox.isChecked());
		// regButton.setEnabled(isFilled);

	}

	@Override
	public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
			int arg3) {

	}

	@Override
	public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
	}


	public void showDatePicker(View v) {
		DialogFragment newFragment = DatePickerFragment.getInstance(
				v.getId(), null, Calendar.getInstance());
		newFragment.show(getSupportFragmentManager(),
				DatePickerFragment.DATE_PICKER_TAG);
	}

	public void showTermsAndConditions(View v) {
		startActivity(new Intent(this, CityauteTermsAndConditions.class));
	}

	private void disableView() {
		dateOfBirthField.setEnabled(false);
		firstNameField.setEnabled(false);
		lastNameField.setEnabled(false);
		usernameField.setEnabled(false);
		emailField.setEnabled(false);
		pwdField.setEnabled(false);
		pwdConfirmField.setEnabled(false);
		countryField.setEnabled(false);
		mobileNumberField.setEnabled(false);
		cityField.setEnabled(false);
		districtField.setEnabled(false);
		streetField.setEnabled(false);
		buildingField.setEnabled(false);
		zipCodeField.setEnabled(false);
		regButton.setEnabled(false);

	}

	private void enableView() {
		dateOfBirthField.setEnabled(true);
		firstNameField.setEnabled(true);
		lastNameField.setEnabled(true);
		usernameField.setEnabled(true);
		emailField.setEnabled(true);
		pwdField.setEnabled(true);
		pwdConfirmField.setEnabled(true);
		countryField.setEnabled(true);
		mobileNumberField.setEnabled(true);
		cityField.setEnabled(true);
		districtField.setEnabled(true);
		streetField.setEnabled(true);
		buildingField.setEnabled(true);
		zipCodeField.setEnabled(true);
		regButton.setEnabled(true);

	}
	
	@Override
	public void onBackPressed() {
		if (ConnectionUtils.isConnecting(mContext, TAG)) {
			enableView();
			setSupportProgressBarIndeterminateVisibility(false);
			Intent loginCancel = new Intent(TAG + HTTPService.CANCEL);
			sendBroadcast(loginCancel);
			ConnectionUtils.clearConnection(mContext, TAG);
		} else
			super.onBackPressed();
	}

	@Override
	public void setCountry(Country country) {
		mCountry=country;	
	}

}
